package com.woniu.airent.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.airent.dto.HouseDto;
import com.woniu.airent.dto.ImgsDto;
import com.woniu.airent.mapper.ExtraMapper;
import com.woniu.airent.mapper.HouseImgMapper;
import com.woniu.airent.mapper.HouseMapper;
import com.woniu.airent.mapper.ItemsMapper;
import com.woniu.airent.service.HouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class HouseServiceImpl implements HouseService {

    public static final int PAGE_SIZE = 3;
    @Autowired
    HouseMapper houseMapper;

    @Autowired
    HouseImgMapper houseImgMapper;

    @Autowired
    ExtraMapper extraMapper;

    @Autowired
    ItemsMapper itemsMapper;

    @Override
    @Transactional
    public String addHouse(HouseDto house) {
        //插入房屋表
        int insert = houseMapper.MyInsert(house);
        System.out.println(house.getHouseId());

        //插入图片表
        List<ImgsDto> imgs = house.getImgs();
        String imgResult = null;
        if (imgs != null) {
            for (ImgsDto img :
                    imgs) {
                int i = houseImgMapper.Myinsert(house.getHouseId(), img.getImgAdress());
                imgResult = i == 0 ? imgResult : "success";
            }
        } else {
            imgResult = "ignore";
        }

        //插入水电燃气
        int exResult = 0;
        if (house.getExtras() != null) {
            exResult = extraMapper.insertExtra(house);
        } else {
            exResult = 1;
        }


        //插入房屋设施
        int itResult = 0;
        if (house.getExtras() != null) {
            itResult = itemsMapper.insertItems(house);
        } else {
            itResult = 1;
        }

        String result = "error";
        if (exResult != 0 && itResult != 0 && imgResult != null && insert != 0) {
            result = "success";
        }
        return result;

    }

    @Override
    public List<HouseDto> findAllHouseByUserId(Integer userId) {
        return houseMapper.selectMyHouseByUserId(userId);
    }

    @Override
    public Integer changeHouseType(String houseNumber) {
        return houseMapper.updateHouseType(houseNumber);
    }

    public PageInfo<HouseDto> showHouse(Integer pageNum, Integer sortMethod){
        PageHelper.startPage(pageNum, PAGE_SIZE);
        List<HouseDto> list = houseMapper.selectSorted(sortMethod);
        return new PageInfo<>(list);
    }


    @Override
    public HouseDto findHouseById(int id) {
        return houseMapper.selectByKey(id);
    }

}
